<?php

/**
 * A key-value registration
 * @author griever
 */
class Joob_Registry_KVP {
	
	private static $instance = null;
	
	protected $data;
	
	private function __construct()	{
		
	}
	
	public static function getInstance()	{
		if (self::$instance == null)	{
			self::$instance = new Joob_Registry_KVP();
		}
		return self::$instance;
	}

	/**
	 * Store a value in an entry
	 * @param string $key the key
	 * @param mixed $value the key
	 * @param mixed $namespace the namespace
	 * @param bool $override should the entry be overriden
	 */
	public function store($key, $value, $namespace = "Joob", $override = true)	{
		$entry = $this->getEntryName($key, $namespace);
		if ($override || !isset($this->data[$entry]))
			$this->data[$entry] = $value;
	}
	
	/**
	 * Get an entry from registry
	 * @param string $key the key
	 * @param mixed $namespace the namespace, could be an array or a string
	 * @param mixed $default the default value, if the entry does not exist
	 */
	public function get($key, $namespace = "Joob", $default = null)	{
		$entry = $this->getEntryName($key, $namespace);
		if (isset($this->data[$entry]))	{
			return $this->data[$entry];
		}
		return $default;
	}
	
	protected function getEntryName($key, $namespace)	{
		if (is_array($namespace))	{
			$namespace = $this->buildNamespace($namespace);
		}
		//remove all nonalphabetical characters
		$key = preg_replace("/[^a-zA-Z]/", "", $key);
		$entry = $namespace.":".$key;
		return $entry;
	}
	
	/**
	 * Build a namespace based on an array
	 * @param array $namespace
	 */
	public function buildNamespace($namespaces)	{
		if (is_array($namespaces))	{
			return implode(":", $namespaces);
		}
		return null;
	}
}

?>